import Module from "./Module"
import CursorMeshModule from "./CursorMeshModule"
import ViewmodeData from "../data/ViewmodeData"
import TourData from "../data/TourData"
import InteractionmodeData from "../data/InteractionmodeData"
import SweepData from "../data/SweepData"
import { DisableCursorMeshCommand } from "../command/cursor.command"
import SettingsData from "../data/SettingsData"
import keyConst from "../constant/key.const"
import { isPanOrMesh } from "../utils/viewmode.util"
export default class CursorController extends Module {
  visibilityRules: (() => boolean)[]
  disabled: boolean
  cursorMesh: CursorMeshModule
  constructor() {
    super(...arguments)
    this.name = "cursor-controller"
    this.visibilityRules = []
    this.disabled = !1
  }
  async init(e, t) {
    this.cursorMesh = await t.getModule(CursorMeshModule)
    this.visibilityRules.push(
      () => {
        const e = t.market.tryGetData(ViewmodeData)
        return !!e && isPanOrMesh(e.closestMode)
      },
      () => {
        const e = t.market.tryGetData(SweepData)
        return !!e && !e.isSweepUnaligned(e.currentSweep)
      },
      () => {
        const e = t.market.tryGetData(TourData)
        return !!e && !e.isTourActive()
      },
      () => {
        const e = t.market.tryGetData(InteractionmodeData)
        return !!e && !e.isMobile()
      },
      () => {
        const e = t.market.tryGetData(SettingsData)
        return !!e && e.tryGetProperty(keyConst.rule.features.cursor, !0)
      }
    )
    this.bindings.push(
      t.commandBinder.addBinding(DisableCursorMeshCommand, async e => {
        this.disabled = e.disable
      })
    )
  }
  onUpdate() {
    this.updateCursorVisibility()
  }
  addVisibilityRule(e) {
    this.visibilityRules.push(e)
  }
  removeVisibilityRule(e) {
    const t = this.visibilityRules.indexOf(e)
    ;-1 !== t && this.visibilityRules.splice(t, 1)
  }
  updateCursorVisibility() {
    const e = !this.disabled && this.visibilityRules.reduce((e, t) => e && t(), !0)
    this.cursorMesh.setVisible(e)
  }
}
